package com.example.statistics.utils

import android.content.Context
import android.database.Cursor
import android.provider.ContactsContract
import android.util.Log
import com.example.statistics.bean.Customer
import com.example.statistics.bean.FolderBean
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

object CustomerUtils {

    suspend fun query(context: Context, body: (List<Customer>) -> Unit) {
        withContext(Dispatchers.IO) {
            var cursor: Cursor? = null
            return@withContext try {
                val resolver = context.contentResolver
                //ContactsContract.CommonDataKinds.Phone.CONTENT_URI
                //ContactsContract.Contacts.CONTENT_URI
                val list = mutableListOf<Customer>()
                cursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null)
                return@withContext cursor?.let {
                    if (it.count > 0) {
                        it.moveToLast()
                        var index = 1
                        do {
                            val bean = Customer()
                            bean.ID = index
                            bean.name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME))
                            //获取联系人手机号
                            bean.phoneOne = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
                            list.add(bean)
                            index += 1
                        } while (it.moveToPrevious())
                        body(list)
                    }
                }

            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                cursor?.close()
            }
        }
    }

}